package com.pang.security.service.impl;

import cn.hutool.core.util.StrUtil;
import com.pang.security.dao.SysUserDao;
import com.pang.security.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * 功能目的描述 ：用于  重写UserDetailsService    ========>>>>>>>>>>>
 * @author： pang-yun
 * @date： 2021-06-22 17:00
 */


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(s)){
            throw new RuntimeException("用户名不能为空");
        }
        //如果不为空，则根据用户名获取用户信息
        SysUser sysUser = sysUserDao.selectByUsername(s);
        if (sysUser==null){
            throw new UsernameNotFoundException(String.format("%s：此用户不存在",s));
        }

        //如果存在，
        //SimpleGrantedAuthority 是GrantedAuthority的实现类
        List<GrantedAuthority> authorities =new ArrayList<>();
        //需要根据用户获取角色， 根据登录的用户获得权限、角色集合
        List<String> codeList =sysUserDao.getRoleCodeByUsername(s);
        codeList.forEach( code -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(code);
            authorities.add(simpleGrantedAuthority);
                }

        );

        return new User(sysUser.getUsername(),sysUser.getPassword(),authorities);
    }
}
